<template>
  <div :class="{ goTop: true, display: show }" @click="goTop">顶部</div>
</template>

<script>
export default {
  data() {
    return {
      show: true,
      throttle: true,
      switch: true,
      clearTimer:0
    };
  },
  mounted() {
    //滚动条滚动事件
    window.addEventListener(
      "scroll",
      () => {
        if (this.throttle) {
          setTimeout(() => {
            this.throttle = true;
            document.body.scrollTop > 145
              ? (this.show = false)
              : (this.show = true);
          }, 100);
          this.throttle = false;
        } else {
          return;
        }
      },
      true
    );
    //鼠标滚动停止滚动条滚动

    window.onmousewheel=document.onmousewheel=(e)=>{
        clearInterval(this.clearTimer);
        this.switch = true;
    }
  },
  watch: {},
  methods: {
    goTop() {
      if (this.switch) {
        let start = document.body.scrollTop;
        const speed = 10;
        this.switch = false;
        this.clearTimer = setInterval(() => {
          if (start - speed <= 0) {
            document.body.scrollTop = 0;
            clearInterval(this.clearTimer);
            this.switch = true
          } else {
            start = start - speed;
            document.body.scrollTop = start;
          }
        }, 5);
      }else{
        return
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.goTop {
  position: fixed;
  z-index: 10;
  bottom: 150px;
  right: 100px;
  width: 50px;
  height: 50px;
  line-height: 50px;
  font-size: 14px;
  text-align: center;
  background-color: rgb(248, 243, 243);
  border-radius: 10px;
  box-shadow: 1px 1px 5px rgb(233, 152, 47);
  cursor: pointer;
}
.display {
  display: none;
}
</style>